package com.anche.cywebnew.Service.systemManager.Impl;

import cn.hutool.core.util.StrUtil;
import com.anche.cywebnew.DAO.systemManager.OrganMapper;
import com.anche.cywebnew.DAO.systemManager.UserMapper;
import com.anche.cywebnew.DTO.SelectDTO;
import com.anche.cywebnew.Pojo.auditManager.NasLog;
import com.anche.cywebnew.Pojo.systemManager.SysOrganization;
import com.anche.cywebnew.Pojo.systemManager.SysResource;
import com.anche.cywebnew.Pojo.systemManager.SysUser;
import com.anche.cywebnew.Service.systemManager.OrganService;
import com.anche.cywebnew.Utils.Exception.RRException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrganServiceImpl implements OrganService {

    @Autowired
    private OrganMapper organMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<SysOrganization> getOrganList(Map<String, Object> map,List<String> cyqxhs) {
        String cyqxh = map.get("cyqxh") == null ? "" : map.get("cyqxh").toString();
        String name = map.get("name") == null ? "" : map.get("name").toString();
        SysOrganization sysOrganization = new SysOrganization();
        sysOrganization.setCyqxh(cyqxh);
        sysOrganization.setName(name);
        return organMapper.selectOrganList(sysOrganization, cyqxhs);
    }
    @Override
    public Page<SysOrganization> getOrganListPage(int page, int limit, SysOrganization sysOrganization){
        Page<SysOrganization> page1 = PageHelper.startPage(page,limit);
        organMapper.selectOrganList(sysOrganization, null);
        return page1;
    }

    @Override
    public void updateOrgan(SysOrganization sysOrganization) {
        organMapper.updateOrganByCyqxh(sysOrganization);
    }

    @Override
    public void addOrgan(SysOrganization sysOrganization) {
        if (organMapper.selectAllCount() > 0) {
            String cyqxh = sysOrganization.getCyqxh();
            int count = organMapper.selectCountByCyqxh(cyqxh);
            if (count == 0) {
                sysOrganization.setCreatedate(new Date());
                organMapper.insertOrgan(sysOrganization);
            } else {
                throw new RRException("此机构编号已存在");
            }
        } else {
            sysOrganization.setCreatedate(new Date());
            organMapper.insertOrgan(sysOrganization);
            SysUser existUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
            SysUser sysUser = new SysUser();
            sysUser.setId(existUser.getId());
            sysUser.setOrgan(sysOrganization.getCyqxh());
            userMapper.updateUserById(sysUser);
        }
    }

    @Override
    public void delOrganByCyqxh(String cyqxh) {
        List<String> idsQuery = new ArrayList<>();
        List<String> idsResult = new ArrayList<>();
        idsQuery.add(cyqxh);
        idsResult.add(cyqxh);
        idsResult = getChildUseRecu(idsQuery, idsResult);
        organMapper.deleteOrganByIds(idsResult);
    }

    @Override
    public List<Object> getTreeOrganization(String cyqxh) {
        List<SysOrganization> sysOrganizations = organMapper.selectOrganList(new SysOrganization(), null);//查出所有资源
        List<Object> list = new ArrayList<>();
        for (SysOrganization t : sysOrganizations) {
            if(StrUtil.isNotEmpty(cyqxh)){
                if (!t.getCyqxh().equals(cyqxh)) {//判断是指定顶级机构
                    continue;
                }
            }else{
                if (!t.getPorgan().equals("-1")) {//判断是否是顶级机构
                    continue;
                }
            }

            JSONObject treeObject = new JSONObject();
            treeObject.put("spread", true);//是否直接展开
            treeObject.put("id", t.getCyqxh());
            treeObject.put("title", t.getName());//tree的节点名称
            treeObject.put("children", getChildren(t.getCyqxh(), sysOrganizations));//子节点，递归遍历
            list.add(treeObject);
        }
        return list;
    }

    @Override
    public String getNameByCyqxh(String cyqxh) {
        return organMapper.selectNameByCyqxh(cyqxh);
    }

    @Override
    public List<String> getListByCyqxh(String cyqxh){
        List<String> idsQuery = new ArrayList<>();
        List<String> idsResult = new ArrayList<>();
        idsQuery.add(cyqxh);
        idsResult.add(cyqxh);
        idsResult = getChildUseRecu(idsQuery, idsResult);

        return idsResult;
    }

    @Override
    public SysOrganization getOneByCyqxh(String cyqxh) {
        return organMapper.selectOneByCyqxh(cyqxh);
    }

    /**
     * 递归遍历所有层级的子集
     *
     * @param idsQuery  要查找的资源id的集合
     * @param idsResult 返回的所有层级的子集资源id的集合
     */
    private List<String> getChildUseRecu(List<String> idsQuery, List<String> idsResult) {
        List<String> childIds = organMapper.getIdsByPids(idsQuery);
        if (childIds.size() > 0) {
            for (String id : childIds) {
                idsResult.add(id);
            }
            getChildUseRecu(childIds, idsResult);
        }
        return idsResult;
    }

    public List<Object> getChildren(String parentId, List<SysOrganization> sysOrganizations) {
        List<Object> list = new ArrayList<>();
        for (SysOrganization d : sysOrganizations) {
            if (d.getPorgan().equals(parentId)) {
                JSONObject obj = new JSONObject();
                obj.put("id", d.getCyqxh());
                obj.put("title", d.getName());
                obj.put("children", getChildren(d.getCyqxh(), sysOrganizations));
                list.add(obj);
            }
        }
        return list;
    }
}
